package com.cs171.market.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.cs171.market.Repository.GodRepository;
import com.cs171.market.entity.God;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

/**
 * @author yangyifei
 * @version 1.0
 * @date 2020/6/21 16:03
 */

@CrossOrigin
@RestController
public class GodController {
    @Autowired
    private GodRepository godRepository;
    private JSONObject result;

    /**
     * 0.登录
     * @return 用户id
     */
    @PostMapping("godlogin")
    public Object login(){
        JSONObject result1 = new JSONObject();
        result1.put("code",200);
        result1.put("id",1);
        return result1;
    }


    /**
     * 1.查询当前用户的数据
     * @return 多条数据
     */
    @GetMapping(value = "/myself",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Object getMyself(){
        result = jsonhead();
        God god = godRepository.findById(1).orElse(null);
        JSONObject jsonGod = (JSONObject) JSON.toJSON(god);
        assert jsonGod != null;
        String addr = jsonGod.getString("address");
        List<String> addrList = Arrays.asList(addr.split(","));
        JSONArray addrArray = (JSONArray) JSON.toJSON(addrList);
        jsonGod.put("address",addrArray);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().add("password");
        result.put("data",jsonGod);
        return JSONObject.toJSONString(result,filter);
    }

    /**
     * 2.修改当前用户的昵称,性别,默认地址,地址列表
     * @return 新昵称
     */
    @PostMapping("myself")
    public Object updateNick(@RequestBody JSONObject jsonParam)
            throws UnsupportedEncodingException {
        Integer id = jsonParam.getInteger("id");
        String sex = jsonParam.getString("gender");
        String act = jsonParam.getString("action");
        String pwd = jsonParam.getString("password");
        String name = jsonParam.getString("nickName");
        String addr0 = jsonParam.getString("defaultAddress");
        String addrs = jsonParam.getString("address");
        String phone = jsonParam.getString("phone");

        God god = godRepository.findById(1).orElse(null);
        if(god != null){
            god.setGname(isEmptyS(name)?god.getGname():name);
            god.setGsex(isEmptyS(sex)?god.getGsex():sex);
            god.setGaddr0(isEmptyS(addr0)?god.getGaddr0():addr0);
            god.setGphone(isEmptyS(phone)?god.getGphone():phone);
            if(!isEmptyS(addrs) && act.equals("add")){
                god.setGaddrs(god.getGaddrs() + "," + addrs);
            }
            else if(!isEmptyS(addrs) && act.equals("delete")){
                String gaddr = god.getGaddrs();
                String naddr = "";
                if (gaddr.contains(addrs)) {
                    Integer idx = gaddr.indexOf(addrs);
                    naddr = gaddr.substring(0, idx);
                    naddr += gaddr.substring(idx + addrs.length());
                    naddr = naddr.replace(",,", ",");
                    if (naddr.charAt(naddr.length() - 1) == ',')
                        naddr = naddr.substring(0, naddr.length() - 1);
                }
                god.setGaddrs(naddr);
            }
            if(!isEmptyS(pwd)){
                Base64.Decoder decoder = Base64.getDecoder();
                String text = new String(decoder.decode(pwd), StandardCharsets.UTF_8);
                god.setGpwd(text);
            }
            godRepository.save(god);
            result = jsonsucc();
            return result;
        }
        result = jsonfail();
        return result;
    }



    /**
     * 重构代码，相似的Json Head
     * @return JsonObject
     */
    private JSONObject jsonhead(){
        JSONObject pAll = new JSONObject();
        pAll.put("success", "true");
        return pAll;
    }

    /**
     * 重构代码，相似的Json success
     * @return JsonObject
     */
    private JSONObject jsonsucc(){
        JSONObject pAll = new JSONObject();
        pAll.put("code", "200");
        return pAll;
    }

    /**
     * 重构代码，相似的Json failure
     * @return JsonObject
     */
    private JSONObject jsonfail(){
        JSONObject pAll = new JSONObject();
        pAll.put("code", "500");
        pAll.put("error", "可能是数据库暂时连接不上，请稍后再试");
        return pAll;
    }

    private boolean isEmptyS(String str1){
        return str1 == null || str1.equals("");
    }
}
